package com.qiriver.demo.mybatisdemo;

import com.qiriver.demo.mybatisdemo.mapper.WxDTO;
import com.qiriver.demo.mybatisdemo.mapper.WxMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@SpringBootApplication
public class MybatisdemoApplication {

	public static void main(String[] args) {
		ApplicationContext ctx = SpringApplication.run(MybatisdemoApplication.class, args);
		// 获取
		SqlSessionFactory sqlSessionFactory = ctx.getBean(SqlSessionFactory.class);
		WxMapper wxMapper = sqlSessionFactory.openSession().getMapper(WxMapper.class);

		List<WxDTO> list = wxMapper.queryAll(2L);
		if (list != null && list.size() > 0) {
			System.out.println(list.get(0));
		}
	}

	/**
	 *  Mybatis初始化流程
	 *
	 */
	@Bean
	public SqlSessionFactory sqlSessionFactory() throws IOException {

		// 1.创建SqlSessionFactoryBuilder实例
		SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

		// 2.通过配置文件生成流来创建SqlSessionFactory
		InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);

		// 3. 添加映射器类，Configuration 可以和SqlSessionFactory互相生成
		Configuration configuration = sqlSessionFactory.getConfiguration();
		configuration.addMapper(WxMapper.class);
		return sqlSessionFactory;
	}










}
